package com.alibaba.csp.sentinel.dashboard.rule.nacos;

/**
 * packageName com.alibaba.csp.sentinel.dashboard.rule.nacos.ClusterServerTransportNacosPublisher
 *
 * @author liudonghai
 * @version JDK 11
 * @date 2025/8/1
 * @description TODO
 */
/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import com.alibaba.csp.sentinel.dashboard.config.NacosRuleConstants;
import com.alibaba.csp.sentinel.dashboard.domain.cluster.config.ServerTransportConfig;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.ConfigType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 集群服务端传输配置 Nacos 发布者
 */
@Component("clusterServerTransportNacosPublisher")
public class ClusterServerTransportNacosPublisher extends com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosPublisher implements DynamicRulePublisher<ServerTransportConfig> {

    @Autowired
    private ConfigService configService;

    @Autowired
    private Converter<ServerTransportConfig, String> converter;

    @Override
    public void publish(String app, ServerTransportConfig config) throws Exception {
        AssertUtil.notEmpty(app, "app name cannot be empty");

        if (config == null) {
            return;
        }

        String configString = converter.convert(config);
        // 测试Nacos连通性和配置信息
        testNacosConnectivity(app, NacosRuleConstants.CLUSTER_SERVER_TRANSPORT_DATA_ID_POSTFIX);

        configService.publishConfig(app + NacosRuleConstants.CLUSTER_SERVER_TRANSPORT_DATA_ID_POSTFIX, NacosRuleConstants.GROUP_ID, configString, ConfigType.JSON.getType());
        testPublishContent(app, NacosRuleConstants.CLUSTER_SERVER_TRANSPORT_DATA_ID_POSTFIX, configString);
    }
}